package com.lottery.ruok.lottrey.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.RechargeThirdRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetPayTypeResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.RechargeThirdResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.StringUtils;
import com.lottery.ruok.lottrey.utils.SystemUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import ui.NavigateBar;
import ui.SquareImageView;
import utils.CashierInputFilter;
import utils.Utils;

/**
 * 人工充值
 */
public class ChargeArtificialActivity extends BaseActivity implements TextWatcher {
    public static final String EXTRA_MONEY = "extra_money";
    public static final String EXTRA_DATA = "EXTRA_DATA";

    @BindView(R.id.qrcode)
    SquareImageView qrcode;
    @BindView(R.id.charge_now)
    RelativeLayout chargeNow;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.certificate)
    EditText certificate;
    @BindView(R.id.tv_tip)
    TextView tipView;
    @BindView(R.id.submit)
    TextView submit;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.money_unit)
    View money_unit;
    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.tv_cure_line)
            View  tvCureLine;
    @BindView(R.id.tv_cure)
    TextView tvTure;


    GetPayTypeResponse.GetPayItemsResponse data;
    private String moneyValue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.transfer_other_lottery_fragment);
        ButterKnife.bind(this);
        init();
        navigateBar.setOnIconClickListener(new NavigateBar.OnIconClickListener() {
            @Override
            public void OnIconClick(View view) {
                //SystemUtil.hiddenInputForce(ChargeArtificialActivity.this);
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                finish();
            }
        });
    }

    private void initData() {

        moneyValue = getIntent().getStringExtra(EXTRA_MONEY);
        data = (GetPayTypeResponse.GetPayItemsResponse) getIntent().getSerializableExtra(EXTRA_DATA);
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (money.getText().length() > 0 && certificate.getText().length() > 0) {
            submit.setTextColor(Color.parseColor("#ffffff"));
            submit.setEnabled(true);
        } else {
            submit.setTextColor(Color.parseColor("#9942F7"));
            submit.setEnabled(false);
        }
    }

    private void init() {
//        if (!Utils.isEmpty(data.getName_alias())) {
//            String result = "";
//            switch (data.getName_alias()) {
//                case "alipay":
//                    result = "支付宝转账";
//                    break;
//                case "tenpay":
//                    result = "财付通转账";
//                    break;
//                case "wechat":
//                    result = "微信转账";
//                    break;
//                default:
//                    result = "转账";
//                    break;
//
//            }
//            navigateBar.setCenterTitle(result);
//        }

        navigateBar.setOnOperateClickListener(new NavigateBar.OnOperateClickListener() {
            @Override
            public void onOperateClick(View view) {
                //如何使用？
                Intent intent = new Intent(ChargeArtificialActivity.this, PayChannelExplainActivity.class);
                startActivity(intent);
            }
        });
        certificate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (data.getIs_voucher().equals("3")) {
                    String editable = certificate.getText().toString();
                    String str = stringFilter(editable.toString());
                    if (!editable.equals(str)) {
                        certificate.setText(str);
                        //设置新的光标所在位置
                        certificate.setSelection(str.length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (money.getText().length() > 0 && certificate.getText().length() > 0) {
                    submit.setTextColor(Color.parseColor("#ffffff"));
                    submit.setEnabled(true);
                } else {
                    submit.setTextColor(Color.parseColor("#9942F7"));
                    submit.setEnabled(false);
                }
            }
        });
        money.addTextChangedListener(this);
        InputFilter[] inputFilters = {new CashierInputFilter()};
        money.setFilters(inputFilters);
        money.setText(moneyValue);

        if (data != null) {
            navigateBar.setCenterTitle(data.getItem_name());
            title.setText(data.getBank_desc() + ":");
            tipView.setText(data.getDesc());
            GlideHelper.loadImageWithoutCache(ChargeArtificialActivity.this, data.getQrcode(), qrcode);

            if (StringUtils.isNotEmpty(data.getRemark())){
                tvTure.setText("备注："+data.getRemark());
                tvTure.setVisibility(View.VISIBLE);
                tvCureLine.setVisibility(View.VISIBLE);
            }else {
                tvTure.setVisibility(View.GONE);
                tvCureLine.setVisibility(View.GONE);
            }
        }

        switch (data.getIs_voucher()) {
            case "1":
                certificate.setInputType(InputType.TYPE_CLASS_NUMBER);
                certificate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                break;
            case "2":
                certificate.setKeyListener(DigitsKeyListener.getInstance("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
                certificate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                break;
            case "3":
                certificate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
                break;
        }
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
// 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        Utils.saveImageLocal(this, data.getQrcode());

        Utils.showToast("二维码图片已保存到本地相册中");

        View decorview = getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bitmap Bmp = decorview.getDrawingCache();
        MediaStore.Images.Media.insertImage(getContentResolver(), Bmp, System.currentTimeMillis() + "", System.currentTimeMillis() + "");
        Utils.showToast("截屏已保存到本地相册中");
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        Utils.showToast("截屏保存失败，请查看是否开启相册存储权限");
    }

    @OnClick({R.id.charge_now, R.id.submit, R.id.money_unit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.money_unit:
                money.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
                money.setSelection(money.getText().length());
                break;

            case R.id.charge_now:
                //把当前图片存储到相册，要多种手机进行测试
                PermissionGen.with(this)
                        .addRequestCode(100)
                        .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request();
                break;
            case R.id.submit:
                if (Utils.parseFloat(money.getText().toString().trim()) < data.getMob_min()) {
                    Utils.showToast("输入金额过小,最小金额为" + data.getMob_min());
                    return;
                }
                if (Utils.parseFloat(money.getText().toString().trim()) > data.getMob_max()) {
                    Utils.showToast("输入金额过大,最大金额为" + data.getMob_max());
                    return;
                }

                if(data.getIs_voucher().equals("3")){
                    int length = certificate.length();
                    int count = StringUtils.getChineseCount(certificate.getText().toString());
                    if(count*2+(length-count)>12){
                        Utils.showToast("请输入12位数字、英文、汉字(汉字占2位)");
                        return;
                    }
                }

                RetrofitBase.getRetrofit().create(RechargeThirdRequest.class)
                        .getResult(UserInfo.getToken(),
                                data.getName_alias(),
                                money.getText().toString(),
                                certificate.getText().toString(),
                                data.getType_id(),
                                data.getId(),
                                data.getQrcode())
                        .compose(RxHelper.<RechargeThirdResponse>handleResult())
                        .subscribe(new RxSubscribe<RechargeThirdResponse>(this) {
                            @Override
                            protected void _onNext(RechargeThirdResponse rechargeThirdResponse) {
                                Utils.showToast(rechargeThirdResponse.getMsg());

                                finish();
                            }

                            @Override
                            protected boolean showDialog() {
                                return true;
                            }
                        });
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    public static void startActivity(Activity activity, GetPayTypeResponse.GetPayItemsResponse data, String money) {
        Intent intent = new Intent(activity, ChargeArtificialActivity.class);

        intent.putExtra(EXTRA_MONEY, money);
        intent.putExtra(EXTRA_DATA, data);
        activity.startActivity(intent);
    }

}
